<template>
  <div class="appointment-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button 
            type="text" 
            @click="$router.back()" 
            class="back-button"
          >
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <h1>预约挂号</h1>
        </div>
        <div class="header-right">
          <el-button-group>
            <el-button 
              :type="viewMode === 'month' ? 'primary' : ''"
              @click="viewMode = 'month'"
            >
              月视图
            </el-button>
            <el-button 
              :type="viewMode === 'week' ? 'primary' : ''"
              @click="viewMode = 'week'"
            >
              周视图
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="appointment-content">
      <div class="content-grid">
        <!-- 左侧筛选区域 -->
        <div class="filter-section">
          <div class="filter-card">
            <div class="card-header">
              <h3><el-icon><Filter /></el-icon>筛选条件</h3>
            </div>
            <div class="card-content">
              <div class="filter-group">
                <label>科室</label>
                <el-select v-model="selectedDepartment" placeholder="选择科室" @change="handleDepartmentChange">
                  <el-option label="全部科室" value="" />
                  <el-option 
                    v-for="dept in departments" 
                    :key="dept.value" 
                    :label="dept.label" 
                    :value="dept.value" 
                  />
                </el-select>
              </div>
              
              <div class="filter-group">
                <label>医生</label>
                <el-select v-model="selectedDoctor" placeholder="选择医生" :disabled="!selectedDepartment">
                  <el-option label="全部医生" value="" />
                  <el-option 
                    v-for="doctor in filteredDoctors" 
                    :key="doctor.id" 
                    :label="doctor.name" 
                    :value="doctor.id" 
                  />
                </el-select>
              </div>
              
              <div class="filter-group">
                <label>时间段</label>
                <el-radio-group v-model="selectedTimeSlot" direction="vertical">
                  <el-radio label="">全天</el-radio>
                  <el-radio label="morning">上午 (08:00-12:00)</el-radio>
                  <el-radio label="afternoon">下午 (14:00-18:00)</el-radio>
                  <el-radio label="evening">晚上 (18:00-21:00)</el-radio>
                </el-radio-group>
              </div>
              
              <el-button type="primary" @click="handleSearch" class="search-button">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </div>
          </div>
          
          <!-- 我的预约 -->
          <div class="filter-card">
            <div class="card-header">
              <h3><el-icon><Calendar /></el-icon>我的预约</h3>
            </div>
            <div class="card-content">
              <div v-if="myAppointments.length > 0" class="appointment-list">
                <div 
                  v-for="appointment in myAppointments" 
                  :key="appointment.id" 
                  class="appointment-item"
                >
                  <div class="appointment-info">
                    <div class="doctor-name">{{ appointment.doctorName }}</div>
                    <div class="appointment-time">
                      {{ formatDateString(appointment.date) }} {{ appointment.time }}
                    </div>
                    <div class="appointment-dept">{{ appointment.department }}</div>
                  </div>
                  <div class="appointment-actions">
                    <el-tag 
                      :type="getStatusType(appointment.status)" 
                      size="small"
                    >
                      {{ getStatusText(appointment.status) }}
                    </el-tag>
                    <el-button 
                      v-if="appointment.status === 'confirmed'"
                      size="small" 
                      type="danger" 
                      text
                      @click="cancelAppointment(appointment.id)"
                    >
                      取消
                    </el-button>
                  </div>
                </div>
              </div>
              <div v-else class="empty-appointments">
                <p>暂无预约记录</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右侧日历区域 -->
        <div class="calendar-section">
          <div class="calendar-card">
            <div class="calendar-header">
              <div class="calendar-nav">
                <el-button 
                  type="text" 
                  @click="previousPeriod"
                  :icon="ArrowLeft"
                />
                <h3>{{ currentPeriodText }}</h3>
                <el-button 
                  type="text" 
                  @click="nextPeriod"
                  :icon="ArrowRight"
                />
              </div>
              <el-button @click="goToToday">今天</el-button>
            </div>
            
            <div class="calendar-content">
              <!-- 月视图 -->
              <div v-if="viewMode === 'month'" class="month-view">
                <div class="weekdays">
                  <div v-for="day in weekdays" :key="day" class="weekday">
                    {{ day }}
                  </div>
                </div>
                <div class="month-grid">
                  <div 
                    v-for="date in monthDates" 
                    :key="date.key"
                    class="date-cell"
                    :class="{
                      'other-month': !date.isCurrentMonth,
                      'today': date.isToday,
                      'selected': date.isSelected,
                      'has-appointments': date.hasAppointments
                    }"
                    @click="selectDate(date)"
                  >
                    <div class="date-number">{{ date.day }}</div>
                    <div v-if="date.hasAppointments" class="appointment-dots">
                      <div 
                        v-for="(dot, index) in date.appointmentDots" 
                        :key="index"
                        class="appointment-dot"
                        :class="dot.type"
                      />
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 周视图 -->
              <div v-else class="week-view">
                <div class="week-header">
                  <div class="time-column">时间</div>
                  <div 
                    v-for="date in weekDates" 
                    :key="date.key"
                    class="week-day-header"
                    :class="{ 'today': date.isToday }"
                  >
                    <div class="day-name">{{ date.dayName }}</div>
                    <div class="day-number">{{ date.day }}</div>
                  </div>
                </div>
                <div class="week-body">
                  <div 
                    v-for="hour in timeSlots" 
                    :key="hour.time"
                    class="time-row"
                  >
                    <div class="time-label">{{ hour.time }}</div>
                    <div 
                      v-for="date in weekDates" 
                      :key="`${date.key}-${hour.time}`"
                      class="time-slot"
                      :class="{
                        'available': isSlotAvailable(date, hour),
                        'booked': isSlotBooked(date, hour)
                      }"
                      @click="selectTimeSlot(date, hour)"
                    >
                      <div 
                        v-if="getSlotAppointment(date, hour)"
                        class="slot-appointment"
                      >
                        {{ getSlotAppointment(date, hour).doctorName }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="appointmentDialogVisible"
      title="预约挂号"
      width="500px"
      :before-close="handleCloseAppointmentDialog"
    >
      <div class="appointment-form">
        <div class="selected-info">
          <h4>预约信息</h4>
          <div class="info-item">
            <span class="label">日期：</span>
            <span class="value">{{ selectedAppointment.date }}</span>
          </div>
          <div class="info-item">
            <span class="label">时间：</span>
            <span class="value">{{ selectedAppointment.time }}</span>
          </div>
          <div class="info-item">
            <span class="label">科室：</span>
            <span class="value">{{ selectedAppointment.department }}</span>
          </div>
          <div class="info-item">
            <span class="label">医生：</span>
            <span class="value">{{ selectedAppointment.doctorName }}</span>
          </div>
          <div class="info-item">
            <span class="label">挂号费：</span>
            <span class="value price">¥{{ selectedAppointment.fee }}</span>
          </div>
        </div>
        
        <el-form :model="appointmentForm" label-width="80px" class="booking-form">
          <el-form-item label="患者姓名">
            <el-input v-model="appointmentForm.patientName" placeholder="请输入患者姓名" />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="appointmentForm.idCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="appointmentForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="症状描述">
            <el-input 
              v-model="appointmentForm.symptoms" 
              type="textarea" 
              :rows="3"
              placeholder="请简要描述症状（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <el-button @click="appointmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAppointment" :loading="booking">
          确认预约
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  ArrowRight,
  Filter,
  Search,
  Calendar
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const viewMode = ref('month')
const currentDate = ref(new Date())
const selectedDate = ref(null)
const selectedDepartment = ref('')
const selectedDoctor = ref('')
const selectedTimeSlot = ref('')
const appointmentDialogVisible = ref(false)
const booking = ref(false)

// 科室数据
const departments = ref([
  { label: '内科', value: 'internal' },
  { label: '外科', value: 'surgery' },
  { label: '儿科', value: 'pediatrics' },
  { label: '妇科', value: 'gynecology' },
  { label: '眼科', value: 'ophthalmology' },
  { label: '耳鼻喉科', value: 'ent' },
  { label: '皮肤科', value: 'dermatology' },
  { label: '骨科', value: 'orthopedics' }
])

// 医生数据
const doctors = ref([
  { id: 1, name: '张医生', department: 'internal', title: '主任医师' },
  { id: 2, name: '李医生', department: 'internal', title: '副主任医师' },
  { id: 3, name: '王医生', department: 'surgery', title: '主治医师' },
  { id: 4, name: '赵医生', department: 'pediatrics', title: '主任医师' },
  { id: 5, name: '陈医生', department: 'gynecology', title: '副主任医师' }
])

// 我的预约
const myAppointments = ref([
  {
    id: 1,
    doctorName: '张医生',
    department: '内科',
    date: '2024-01-20',
    time: '09:00',
    status: 'confirmed'
  },
  {
    id: 2,
    doctorName: '李医生',
    department: '内科',
    date: '2024-01-25',
    time: '14:30',
    status: 'pending'
  }
])

// 预约表单
const appointmentForm = reactive({
  patientName: '',
  idCard: '',
  phone: '',
  symptoms: '',
  scheduleId: null, // 添加scheduleId字段
  doctorId: null,   // 添加doctorId字段
  appointmentDate: '',
  timeSlot: ''
})

// 选中的预约信息
const selectedAppointment = reactive({
  date: '',
  time: '',
  department: '',
  doctorName: '',
  fee: 50
})

// 星期名称
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 时间段
const timeSlots = [
  { time: '08:00' }, { time: '08:30' }, { time: '09:00' }, { time: '09:30' },
  { time: '10:00' }, { time: '10:30' }, { time: '11:00' }, { time: '11:30' },
  { time: '14:00' }, { time: '14:30' }, { time: '15:00' }, { time: '15:30' },
  { time: '16:00' }, { time: '16:30' }, { time: '17:00' }, { time: '17:30' },
  { time: '18:00' }, { time: '18:30' }, { time: '19:00' }, { time: '19:30' }
]

// 计算属性
const currentPeriodText = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth() + 1
  
  if (viewMode.value === 'month') {
    return `${year}年${month}月`
  } else {
    // 周视图显示周的起始和结束日期
    const startOfWeek = getStartOfWeek(currentDate.value)
    const endOfWeek = new Date(startOfWeek)
    endOfWeek.setDate(startOfWeek.getDate() + 6)
    
    return `${formatDate(startOfWeek)} - ${formatDate(endOfWeek)}`
  }
})

const filteredDoctors = computed(() => {
  if (!selectedDepartment.value) return []
  return doctors.value.filter(doctor => doctor.department === selectedDepartment.value)
})

const monthDates = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)
  const startDate = getStartOfWeek(firstDay)
  const dates = []
  
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)
    
    const isCurrentMonth = date.getMonth() === month
    const isToday = isSameDay(date, new Date())
    const isSelected = selectedDate.value && isSameDay(date, selectedDate.value)
    
    dates.push({
      key: date.toISOString(),
      day: date.getDate(),
      date: date,
      isCurrentMonth,
      isToday,
      isSelected,
      hasAppointments: hasAppointmentsOnDate(date),
      appointmentDots: getAppointmentDots(date)
    })
  }
  
  return dates
})

const weekDates = computed(() => {
  const startOfWeek = getStartOfWeek(currentDate.value)
  const dates = []
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(startOfWeek)
    date.setDate(startOfWeek.getDate() + i)
    
    dates.push({
      key: date.toISOString(),
      day: date.getDate(),
      date: date,
      dayName: weekdays[date.getDay()],
      isToday: isSameDay(date, new Date())
    })
  }
  
  return dates
})

// 方法
const getStartOfWeek = (date) => {
  const d = new Date(date)
  const day = d.getDay()
  const diff = d.getDate() - day
  return new Date(d.setDate(diff))
}

const isSameDay = (date1, date2) => {
  return date1.toDateString() === date2.toDateString()
}

const formatDate = (date) => {
  // 确保传入的是Date对象
  if (typeof date === 'string') {
    date = new Date(date)
  }
  if (!(date instanceof Date) || isNaN(date.getTime())) {
    return '无效日期'
  }
  return date.toLocaleDateString('zh-CN', {
    month: 'long',
    day: 'numeric'
  })
}

// 专门用于格式化字符串日期的函数
const formatDateString = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) {
    return dateStr // 如果无法解析，返回原字符串
  }
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const hasAppointmentsOnDate = (date) => {
  // 模拟数据：检查指定日期是否有预约
  const dateStr = date.toISOString().split('T')[0]
  return myAppointments.value.some(apt => apt.date === dateStr)
}

const getAppointmentDots = (date) => {
  // 返回预约点的样式信息
  if (hasAppointmentsOnDate(date)) {
    return [{ type: 'confirmed' }]
  }
  return []
}

const isSlotAvailable = (date, hour) => {
  // 检查时间段是否可预约
  return !isSlotBooked(date, hour)
}

const isSlotBooked = (date, hour) => {
  // 检查时间段是否已被预约
  const dateStr = date.date.toISOString().split('T')[0]
  return myAppointments.value.some(apt => 
    apt.date === dateStr && apt.time === hour.time
  )
}

const getSlotAppointment = (date, hour) => {
  const dateStr = date.date.toISOString().split('T')[0]
  return myAppointments.value.find(apt => 
    apt.date === dateStr && apt.time === hour.time
  )
}

const getStatusType = (status) => {
  const statusMap = {
    confirmed: 'success',
    pending: 'warning',
    completed: 'info',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    confirmed: '已确认',
    pending: '待确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const previousPeriod = () => {
  if (viewMode.value === 'month') {
    currentDate.value.setMonth(currentDate.value.getMonth() - 1)
  } else {
    currentDate.value.setDate(currentDate.value.getDate() - 7)
  }
  currentDate.value = new Date(currentDate.value)
}

const nextPeriod = () => {
  if (viewMode.value === 'month') {
    currentDate.value.setMonth(currentDate.value.getMonth() + 1)
  } else {
    currentDate.value.setDate(currentDate.value.getDate() + 7)
  }
  currentDate.value = new Date(currentDate.value)
}

const goToToday = () => {
  currentDate.value = new Date()
}

const selectDate = (date) => {
  selectedDate.value = date.date
}

const selectTimeSlot = (date, hour) => {
  if (!isSlotAvailable(date, hour)) return
  
  // 设置预约信息
  selectedAppointment.date = formatDate(date.date)
  selectedAppointment.time = hour.time
  selectedAppointment.department = selectedDepartment.value ? 
    departments.value.find(d => d.value === selectedDepartment.value)?.label || '内科' : '内科'
  selectedAppointment.doctorName = selectedDoctor.value ? 
    doctors.value.find(d => d.id === selectedDoctor.value)?.name || '张医生' : '张医生'
  
  // 设置表单数据
  appointmentForm.doctorId = selectedDoctor.value || 1
  appointmentForm.scheduleId = `${selectedDepartment.value || 'internal'}_${selectedDoctor.value || 1}_${date.date.toISOString().split('T')[0]}_${hour.time}`
  appointmentForm.appointmentDate = date.date.toISOString().split('T')[0]
  appointmentForm.timeSlot = hour.time
  
  appointmentDialogVisible.value = true
}

const handleDepartmentChange = () => {
  selectedDoctor.value = ''
}

const handleSearch = () => {
  ElMessage.success('搜索功能开发中...')
}

const validateForm = () => {
  const errors = []
  
  if (!appointmentForm.patientName?.trim()) {
    errors.push('患者姓名不能为空')
  }
  
  if (!appointmentForm.idCard?.trim()) {
    errors.push('身份证号不能为空')
  } else if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(appointmentForm.idCard)) {
    errors.push('身份证号格式不正确')
  }
  
  if (!appointmentForm.phone?.trim()) {
    errors.push('手机号不能为空')
  } else if (!/^1[3-9]\d{9}$/.test(appointmentForm.phone)) {
    errors.push('手机号格式不正确')
  }
  
  if (!appointmentForm.scheduleId || !appointmentForm.doctorId) {
    errors.push('预约信息不完整，请重新选择时间段')
  }
  
  return errors
}

const confirmAppointment = async () => {
  const validationErrors = validateForm()
  
  if (validationErrors.length > 0) {
    ElMessage.warning(validationErrors[0])
    return
  }
  
  booking.value = true
  
  try {
    // 构建预约数据
    const appointmentData = {
      doctorId: appointmentForm.doctorId,
      scheduleId: appointmentForm.scheduleId,
      appointmentDate: appointmentForm.appointmentDate,
      timeSlot: appointmentForm.timeSlot,
      symptoms: appointmentForm.symptoms || '',
      patientName: appointmentForm.patientName,
      idCard: appointmentForm.idCard,
      phone: appointmentForm.phone
    }
    
    console.log('发送预约数据:', appointmentData)
    
    // 使用userStore的createAppointment方法进行真实API调用
    const result = await userStore.createAppointment(appointmentData)
    
    if (result.success) {
      ElMessage.success('预约成功！')
      appointmentDialogVisible.value = false
      
      // 重新加载预约列表
      await userStore.loadAppointments()
      
      // 重置表单
      Object.assign(appointmentForm, {
        patientName: '',
        idCard: '',
        phone: '',
        symptoms: '',
        scheduleId: null,
        doctorId: null,
        appointmentDate: '',
        timeSlot: ''
      })
    } else {
      // 根据错误信息提供更友好的提示
      let errorMessage = result.message || '预约失败，请稍后重试'
      
      if (errorMessage.includes('scheduleId')) {
        errorMessage = '预约时间段信息有误，请重新选择时间段'
      } else if (errorMessage.includes('doctorId')) {
        errorMessage = '医生信息有误，请重新选择医生'
      } else if (errorMessage.includes('已被预约')) {
        errorMessage = '该时间段已被预约，请选择其他时间'
      } else if (errorMessage.includes('参数')) {
        errorMessage = '预约信息不完整，请检查填写内容'
      }
      
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('预约失败:', error)
    
    // 根据错误类型提供不同的提示
    let errorMessage = '预约失败，请稍后重试'
    
    if (error.code === 'NETWORK_ERROR') {
      errorMessage = '网络连接失败，请检查网络后重试'
    } else if (error.code === 'TIMEOUT') {
      errorMessage = '请求超时，请稍后重试'
    } else if (error.response?.status === 400) {
      errorMessage = '请求参数有误，请检查预约信息'
    } else if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
    } else if (error.response?.status === 500) {
      errorMessage = '服务器错误，请稍后重试'
    }
    
    ElMessage.error(errorMessage)
  } finally {
    booking.value = false
  }
}

const cancelAppointment = async (appointmentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个预约吗？',
      '取消预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 使用userStore的cancelAppointment方法进行真实API调用
    const result = await userStore.cancelAppointment(appointmentId)
    
    if (result.success) {
      ElMessage.success('预约已取消')
      // 重新加载预约列表
      await userStore.loadAppointments()
    } else {
      ElMessage.error(result.message || '取消预约失败，请稍后重试')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error('取消预约失败，请稍后重试')
    }
    // 用户取消操作时不显示错误
  }
}

const handleCloseAppointmentDialog = () => {
  appointmentDialogVisible.value = false
  Object.assign(appointmentForm, {
    patientName: '',
    idCard: '',
    phone: '',
    symptoms: '',
    scheduleId: null,
    doctorId: null,
    appointmentDate: '',
    timeSlot: ''
  })
}

// 监听userStore中的预约数据变化
watch(
  () => userStore.appointments,
  (newAppointments) => {
    myAppointments.value = newAppointments || []
  },
  { immediate: true }
)

onMounted(async () => {
  // 初始化数据
  try {
    // 加载用户预约数据
    await userStore.loadAppointments()
  } catch (error) {
    console.error('加载预约数据失败:', error)
  }
})
</script>

<style scoped>
.appointment-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409eff;
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.appointment-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

.content-grid {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.filter-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-content {
  padding: 20px;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #2c3e50;
}

.filter-group .el-select,
.filter-group .el-radio-group {
  width: 100%;
}

.search-button {
  width: 100%;
}

.appointment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.appointment-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 3px solid #409eff;
}

.appointment-info {
  margin-bottom: 10px;
}

.doctor-name {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.appointment-time {
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 2px;
}

.appointment-dept {
  font-size: 12px;
  color: #909399;
}

.appointment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-appointments {
  text-align: center;
  padding: 30px;
  color: #909399;
}

.calendar-section {
  min-height: 600px;
}

.calendar-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  height: 100%;
}

.calendar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.calendar-nav {
  display: flex;
  align-items: center;
  gap: 15px;
}

.calendar-nav h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  min-width: 200px;
  text-align: center;
}

.calendar-content {
  padding: 20px;
}

/* 月视图样式 */
.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  margin-bottom: 10px;
}

.weekday {
  padding: 10px;
  text-align: center;
  font-weight: 600;
  color: #7f8c8d;
  background: #f8f9fa;
}

.month-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background: #e4e7ed;
}

.date-cell {
  background: white;
  min-height: 80px;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
  position: relative;
}

.date-cell:hover {
  background: #f0f9ff;
}

.date-cell.other-month {
  color: #c0c4cc;
  background: #fafafa;
}

.date-cell.today {
  background: #ecf5ff;
}

.date-cell.selected {
  background: #409eff;
  color: white;
}

.date-cell.has-appointments {
  background: #f0f9ff;
}

.date-number {
  font-weight: 500;
  margin-bottom: 4px;
}

.appointment-dots {
  display: flex;
  gap: 2px;
  flex-wrap: wrap;
}

.appointment-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #409eff;
}

.appointment-dot.confirmed {
  background: #67c23a;
}

.appointment-dot.pending {
  background: #e6a23c;
}

/* 周视图样式 */
.week-header {
  display: grid;
  grid-template-columns: 80px repeat(7, 1fr);
  gap: 1px;
  margin-bottom: 10px;
}

.time-column {
  padding: 10px;
  text-align: center;
  font-weight: 600;
  color: #7f8c8d;
  background: #f8f9fa;
}

.week-day-header {
  padding: 10px;
  text-align: center;
  background: #f8f9fa;
}

.week-day-header.today {
  background: #ecf5ff;
  color: #409eff;
}

.day-name {
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 2px;
}

.day-number {
  font-weight: 600;
  font-size: 16px;
}

.week-body {
  display: flex;
  flex-direction: column;
  gap: 1px;
  background: #e4e7ed;
}

.time-row {
  display: grid;
  grid-template-columns: 80px repeat(7, 1fr);
  gap: 1px;
}

.time-label {
  padding: 15px 10px;
  text-align: center;
  font-size: 12px;
  color: #7f8c8d;
  background: #f8f9fa;
}

.time-slot {
  background: white;
  min-height: 50px;
  padding: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.time-slot:hover {
  background: #f0f9ff;
}

.time-slot.available {
  background: #f0f9ff;
}

.time-slot.booked {
  background: #fef0f0;
  cursor: not-allowed;
}

.slot-appointment {
  font-size: 12px;
  color: #f56c6c;
  text-align: center;
}

/* 预约对话框样式 */
.appointment-form {
  max-height: 500px;
  overflow-y: auto;
}

.selected-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.selected-info h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-item .label {
  color: #7f8c8d;
}

.info-item .value {
  font-weight: 500;
  color: #2c3e50;
}

.info-item .price {
  color: #f56c6c;
  font-weight: 600;
}

.booking-form {
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-grid {
    grid-template-columns: 280px 1fr;
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .appointment-content {
    padding: 20px 15px;
  }
  
  .content-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .filter-section {
    order: 2;
  }
  
  .calendar-section {
    order: 1;
  }
  
  .header-content {
    padding: 0 10px;
  }
  
  .header-left h1 {
    font-size: 20px;
  }
  
  .date-cell {
    min-height: 60px;
  }
  
  .time-slot {
    min-height: 40px;
  }
}
</style>